"""
配置管理模块
"""

import yaml
from pathlib import Path
from typing import Any, Dict


class Config:
    """配置管理类"""
    
    _instance = None
    _config = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if self._config is None:
            self.load_config()
    
    def load_config(self, config_path: str = "config.yaml"):
        """加载配置文件"""
        try:
            config_file = Path(config_path)
            if not config_file.exists():
                raise FileNotFoundError(f"配置文件不存在: {config_path}")
            
            with open(config_file, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f)
            
            print(f"[配置] 已加载配置文件: {config_path}")
        except Exception as e:
            print(f"[错误] 加载配置文件失败: {e}")
            self._config = self._get_default_config()
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置项
        支持点号分隔的嵌套键，例如: 'model.default_type'
        """
        if self._config is None:
            return default
        
        keys = key.split('.')
        value = self._config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any):
        """设置配置项"""
        if self._config is None:
            self._config = {}
        
        keys = key.split('.')
        config = self._config
        
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
    
    def save(self, config_path: str = "config.yaml"):
        """保存配置到文件"""
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                yaml.dump(self._config, f, allow_unicode=True, default_flow_style=False)
            print(f"[配置] 已保存配置文件: {config_path}")
        except Exception as e:
            print(f"[错误] 保存配置文件失败: {e}")
    
    @staticmethod
    def _get_default_config() -> Dict:
        """获取默认配置"""
        return {
            'app': {
                'name': 'Segment Anything 图片分割工具',
                'version': '4.0',
                'window_width': 1400,
                'window_height': 900
            },
            'model': {
                'default_type': 'vit_b',
                'models_dir': 'models'
            },
            'logging': {
                'level': 'INFO',
                'file': 'logs/app.log'
            }
        }
    
    def __getitem__(self, key: str) -> Any:
        """支持字典式访问"""
        return self.get(key)
    
    def __setitem__(self, key: str, value: Any):
        """支持字典式设置"""
        self.set(key, value)

